package com.ganee.agora.view.fragment


import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.launcher.ARouter

import com.ganee.agora.R
import com.ganee.agora.adapter.HomeAdapter
import com.ganee.agora.event.PostEvent
import com.ganee.agora.model.HomeListBean
import com.ganee.agora.viewmodel.HomeViewModel
import com.ganee.baselib.mvvmlibrary.base.BaseFragment
import kotlinx.android.synthetic.main.fragment_home.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/** 首页
 * A simple [Fragment] subclass.
 */
class HomeFragment : BaseFragment<HomeViewModel>() {

    private var mAdapter: HomeAdapter? = null
    private val mList = mutableListOf<HomeListBean>()

    override fun getViewModel(): HomeViewModel {
        return ViewModelProviders.of(this).get(HomeViewModel::class.java)
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        // Inflate the layout for this fragment
        val view = inflater.inflate(R.layout.fragment_home, container, false)
        return view
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        ARouter.getInstance().inject(this)
        EventBus.getDefault().register(this)
        initViewAndAdapter()
        initRequestData()
    }

    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        initRequestData()
    }

    private fun initRequestData() {
        viewModel.getHomeList()
        viewModel.home.observe(this, Observer<List<HomeListBean>> { registerCompanyEntities ->
            mList.clear()
            mList.addAll(registerCompanyEntities)
            mAdapter!!.notifyDataSetChanged()
        })
    }

    override fun onDestroyView() {
        super.onDestroyView()
        EventBus.getDefault().unregister(this)
    }
    private fun initViewAndAdapter() {
        homeRecyclerView.setHasFixedSize(true)
        homeRecyclerView.layoutManager = LinearLayoutManager(activity)

        mAdapter = HomeAdapter(mList)
        homeRecyclerView.adapter = mAdapter
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public fun onReload(event:PostEvent){
        initRequestData()
    }
}
